package com.guxingke.typecho4j.widget.handle.content;

import java.io.File;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.jfinal.model.Content;
import com.guxingke.typecho4j.route.Route;
import com.guxingke.typecho4j.route.Routes;
import com.guxingke.typecho4j.widget.WidgetHandle;
import com.guxingke.typecho4j.widget.provider.ContentBaseWidget;
import com.jfinal.core.Controller;
import com.jfinal.kit.PathKit;

/**
 * 新增评论处理组件
 * 
 * @author guxingke
 * */
public class FileDeleteHandleWidget extends ContentBaseWidget implements
		WidgetHandle {

	@Override
	public void handle(Controller controller) throws Typecho4jException {
		String fileName = deleteDbInfo(controller);

		String filePath = PathKit.getWebRootPath() + File.separator
				+ constants.getUploadPath() + File.separator
				+ fileName;
		boolean deleteFlag = deleteFile(filePath);

		if (filePath == null || !deleteFlag) {
			controller.setAttr("error", "删除出错");
		}

		controller.renderJson();
	}

	private boolean deleteFile(String filePath) {
		File file = new File(filePath);
		if (file.exists() && file.isFile()) {
			return file.delete();
		}
		return false;
	}

	private String deleteDbInfo(Controller controller) {
		String result = null;
		Long cid = controller.getParaToLong("cid");
		if (cid != null) {
			Content content = Content.dao.findById(cid);
			result = content.getStr("title");
			content.delete();
		}
		return result;
	}

	@Override
	public void configRoute(Routes routes) {
		routes.addRoute(new Route("delete", this.getClass(), null));
	}
}
